﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using LogSystem;
using UnityEngine;
using Yoozoo.HRP.Runtime;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Core.Common
{
    public static class LoadingUtils
    {
        private static float ori_Buget;
        private static int btConst = 10;
        public static LoadingTaskManager LoadingTaskManager => LoadingTaskManager.Inst;

        private static bool loadingUIShowing = false;

        private static Dictionary<HCamera, LayerMask> cameraLayerMaskMap = new Dictionary<HCamera, LayerMask>(10);

        public static void AddLoaderNameType(string loaderName,int type)
        {
            LoadingTaskManager.AddLoaderNameType(loaderName,type);
        }

        public static SmartResLoader AddLoadTask(string taskName)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading,$"加载任务名为空！！");
                return null;
            }
            return LoadingTaskManager.AddLoadTask(taskName);
        }
        

        public static SmartResLoader AddLoadTask(string taskName, string resPath, Res.ResLoadCompleteCallBack callback = null)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading,$"加载任务名为空！！");
                return null;
            }
            return LoadingTaskManager.AddLoadTask(taskName, resPath, callback);
        }
        
        public static SmartResLoader AddLoadTask(string taskName, List<string> resPaths,Res.ResLoadCompleteCallBack callBack = null,
            Action completeCallback = null)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading,$"加载任务名为空！！");
                return null;
            }
            return LoadingTaskManager.AddLoadTask(taskName, resPaths, callBack,completeCallback);
        }

        public static LoadConstructTask AddConstructTask(string taskName, Action action,int type)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading,$"构建任务名为空！！");
                return null;
            }
            return LoadingTaskManager.AddConstructTask(taskName, action, type);
        }

        public static void RemoveConstructTask(string taskName)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading,$"构建任务名为空！！");
                return;
            }

            LoadingTaskManager.RemoveConstructTask(taskName);
        }
        
        public static void DisposeLoadingLoaders()
        {
            LoadingTaskManager.Dispose(false);
        }

        public static void DisposeAll()
        {
            LoadingTaskManager.Dispose(true);
        }

        public static void OnEnterScene(string sceneName)
        {
            LoadingTaskManager.OnEnterScene(sceneName);
        }
        
        public static void OnLoadingUIShow()
        {
            loadingUIShowing = true;
        }

        public static void OnLoadingUIHide()
        {
            loadingUIShowing = false;
            //
            // // 还原相机的LayerMask
            // foreach (var cm in cameraLayerMaskMap)
            // {
            //     if (cm.Key && cm.Key.Camera)
            //     {
            //         if (cm.Key.Camera.cullingMask == 0) // 如果中途有过更改，不处理
            //         {
            //             cm.Key.Camera.cullingMask = cm.Value;
            //         }
            //     }
            // }
            // cameraLayerMaskMap.Clear();
        }
        
        public static void OnCameraEnable(HCamera hCamera)
        {
            // if (loadingUIShowing)
            // {
            //     if (!hCamera.IsSpareCamera && hCamera.MarkString != "UICamera")
            //     {
            //         if (hCamera.Camera && !cameraLayerMaskMap.ContainsKey(hCamera))
            //         {
            //             cameraLayerMaskMap.Add(hCamera, hCamera.Camera.cullingMask);
            //             hCamera.Camera.cullingMask = 0;
            //         }
            //     }
            // }

            if (hCamera.MarkString == "EmptyBaseCamera")
            {
                if (QualitySettings.streamingMipmapsActive)
                {
                    // ori_Buget = QualitySettings.streamingMipmapsMemoryBudget;
                    // Texture.streamingTextureDiscardUnusedMips = true;
                    // QualitySettings.streamingMipmapsMemoryBudget = btConst;
                }
            }
            
            //Timers.inst.CallLater((o =>
            //{
                if (LoadingTaskManager != null && !LoadingTaskManager.enterSceneSuccess)
                {
                    if (hCamera.enabled && !hCamera.IsSpareCamera)
                    {
                        //Debug.LogError(LogModule.Loading,$"在Loading时开启了摄像机：{hCamera.transform.name}",hCamera.gameObject);
                    }
                }
            //} ));
        }

        public static void OnCameraDisable(HCamera hCamera)
        {
            if (hCamera.MarkString == "EmptyBaseCamera")
            {
                if (QualitySettings.streamingMipmapsActive)
                {
                   // QualitySettings.streamingMipmapsMemoryBudget = ori_Buget;
                }
            }
        }

        public static void DisposeTask(string taskName)
        {
            if (string.IsNullOrEmpty(taskName))
            {
                Debug.LogError(LogModule.Loading, $"加载任务名为空！！");
                return;
            }
            LoadingTaskManager.DisposeTask(taskName);
        }

        // 测试用
        public static void DisposeAllLoadingLoaders()
        {
            LoadingTaskManager.DisposeAll();
        }
        
        
        private static Dictionary<string,long> _recodeTimeDic = null;
        //[Conditional("DEBUG")]
        public static void RecodeTimeStart(string recodeName)
        {
            if (_recodeTimeDic == null)
            {
                _recodeTimeDic = new Dictionary<string, long>();
            }
            if (_recodeTimeDic.ContainsKey(recodeName))
            {
                UnityEngine.Debug.LogWarning("recodeName has exits:" + recodeName);
            }
            if(_recodeTimeDic.TryAdd(recodeName,DateTime.Now.Ticks))
            {
                Debug.Log(LogModule.Loading,$"记录时间：{recodeName}");
            }
        }
        //[Conditional("DEBUG")]
        public static void RecodeTimeEnd(string recodeName)
        {
            if (_recodeTimeDic == null)
            {
                _recodeTimeDic = new Dictionary<string, long>();
            }
            if (_recodeTimeDic.TryGetValue(recodeName, out var time))
            {
                Debug.Log(LogModule.Loading,$"记录时间结束：{recodeName} 花费时长：{new TimeSpan(DateTime.Now.Ticks - time).TotalMilliseconds}ms");
                _recodeTimeDic.Remove(recodeName);
            }
            else
            {
                Debug.LogWarning("recodeName not exits:" + recodeName);
            }
        }
    }
}
